﻿using System.Drawing;
using XFControls.Utils;

namespace XFControls.XFPanels.XFPanelItems
{
    public class XFItemSimpleText : XFItemBase
    {
        private int _height;

        public XFItemSimpleText()
        {
            init();
        }

        public XFItemSimpleText(string text)
        {
            Text = text;
            init();
        }

        public string Text { get; private set; }

        private void init()
        {
            _height = -1;

            Style = new XFItemStyle
                        {
                            SelectedBackgroundAlign = XFItemBackgroundAlign.Center,
                            TextFont = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular)
                        };

            ItemType = XFItemType.Display;
        }

        public void SetString(string text)
        {
            Text = text;
            ResetHeight();
        }

        public override int GetHeight()
        {
            if (!Visible)
                return 0;

            if (_height > 0)
                return _height;

            int width = GetWidth() - (Style.PaddingLeft + Style.PaddingRight);
            _height = Style.TextFont.MeasureString(Text, new Rectangle(0, 0, width, 0)).Height + 5 + Style.PaddingTop + Style.PaddingBottom;

            if (Buffer == null)
                Buffer = XFBitmapFactory.GetBitmap(GetWidth(false), _height);

            return _height;
        }

        public override void ResetHeight()
        {
            _height = -1;
        }

        public override void ItemPaint(Graphics g, int x, int y)
        {
            base.ItemPaint(g, x, y);

            int width = GetWidth() - (Style.PaddingLeft + Style.PaddingRight);

            using (var p = new Pen(Color.Black))
            {
                g.DrawLine(p, 0, y + (_height - 1), GetWidth(), y + (_height - 1));
            }
            g.DrawString(Text, new Rectangle(x + Style.PaddingLeft, y + 2 + Style.PaddingTop, width, GetHeight()), Style);
        }
    }
}